package com.imooc.router.asm

import java.io.File

/**
 *@author: xiaosy
 *时间: 2024/11/13
 *@Description: java类作用描述
 *@Version: 1.0
 **/
class RouterMappingCollector {
    private val PACKAGE_NAME = "com/imooc/router/mapping"
    private val CLASS_NAME_PREFIX = "RouterMapping_"
    private val CLASS_FILE_SUFFIX = ".class"

    private val mappingClassNames = HashSet<String>()

    /**
     * 获取收集好的映射表类名
     * @return
     */
    fun getMappingClassName(): Set<String> {
        return mappingClassNames
    }

    /**
     * 收集class文件或者class文件目录中的映射表类。
     * @param classFile
     */
    fun collect(classFile: File) {
        if (classFile.absolutePath.contains(PACKAGE_NAME)
            && classFile.name.startsWith(CLASS_NAME_PREFIX)
            && classFile.name.endsWith(CLASS_FILE_SUFFIX)
        ) {
            val className = classFile.name.replace(CLASS_FILE_SUFFIX, "")
            mappingClassNames.add(className)
            println("collect classFile >>> add File")
        }
    }

    /**
     * 收集JAR包中的目标类
     * @param jarFile
     */
    fun collectFromJarFile(entryName: String) {
        if (isMappingJarFile(entryName)) {
            val className = entryName
                .replace(PACKAGE_NAME, "")
                .replace("/", "")
                .replace(CLASS_FILE_SUFFIX, "")
            mappingClassNames.add(className)
        }
    }

    fun isMappingJarFile(entryName: String): Boolean {
        return (entryName.contains(PACKAGE_NAME)
                && entryName.contains(CLASS_NAME_PREFIX)
                && entryName.contains(CLASS_FILE_SUFFIX))

    }
}